//
//  MenuButton.swift
//  HisPaste
//
//  Created by 烟雀 on 2024/2/16.
//
//  状态栏菜单按钮
//

import Foundation
import SwiftUI

class MenuButton{
    
    var statusItem: NSStatusItem?
    var popOver = NSPopover()
    
    func makeMenuButton() {
        popOver.behavior = .transient
        popOver.animates = true
        popOver.contentViewController = NSViewController()
        popOver.contentViewController?.view = NSHostingView(rootView: SettingsView())
        popOver.contentSize = NSSize(width: 260, height: 800)
        statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
        if let menuButton = statusItem?.button{
            menuButton.image = NSImage(named: "MenuButtonIcon")
            menuButton.image?.isTemplate = true  // change image color to surrounding environment
            // 自定义按钮 需显示设置目标
            // 否则 会找不到目标(多半会找 AppDelegate)
            menuButton.target = self
            menuButton.action = #selector(MenuButtonToggle)
        }
    }
    
    @objc func MenuButtonToggle(sender: AnyObject) {
        //      showing popover
        if popOver.isShown{
            popOver.performClose(sender)
        }else{
            //Top Get Button Location for popover arrow
            self.popOver.show(relativeTo: (statusItem?.button!.bounds)!, of: (statusItem?.button!)!, preferredEdge: NSRectEdge.minY)
        }
    }
}

